package com.blb.common.controller;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

/**
 * @author lvtian
 * @date 2022/11/28 15:35
 */
@WebServlet("/code.do")
public class CodeServlet extends HttpServlet {
    public static final int WIDTH = 100;
    public static final int HEIGHT = 40;
    public static final int FONT_SIZE = 20;
    public static final String CHARS = "ABCDEFGHIJKLMNPQRSTUVWXYZ123456789";
    public static final Color[] COLORS = {Color.PINK,Color.YELLOW,Color.MAGENTA,Color.GREEN,Color.BLACK,Color.RED};

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //创建图片对象
        BufferedImage image = new BufferedImage(WIDTH,HEIGHT,BufferedImage.TYPE_INT_ARGB);
        //获得绘图对象
        Graphics graphics = image.getGraphics();
        //设置背景色
        graphics.setColor(Color.GRAY);
        //填充长方形
        graphics.fillRect(0,0,WIDTH,HEIGHT);
        //设置字体
        graphics.setFont(new Font("黑体", Font.ITALIC,FONT_SIZE));
        Random random = new Random();
        StringBuilder stringBuilder = new StringBuilder();
        //随机生成4个文字，绘制到图片上
        for (int i = 0; i < 4; i++) {
            //随机字母
            char c = CHARS.charAt(random.nextInt(CHARS.length()));
            stringBuilder.append(c);
            //颜色随机
            graphics.setColor(COLORS[random.nextInt(COLORS.length)]);
            //绘制字母
            graphics.drawString(String.valueOf(c),FONT_SIZE * i + 10 ,FONT_SIZE);
        }
        //保存验证码到Session中
        req.getSession().setAttribute("code",stringBuilder.toString());
        //设置不缓存图片的响应头
        resp.addHeader("Cache-Control","no-cache");
        //将图片通过输出流发给浏览器
        ImageIO.write(image,"PNG",resp.getOutputStream());

    }
}
